﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace zzOSSSynch
{
    class Program
    {
        private static string rootPath = System.Configuration.ConfigurationManager.AppSettings["rootPath"].ToString();
        private static float maxSizeM = float.Parse(System.Configuration.ConfigurationManager.AppSettings["maxSize"].ToString());

        private static string baseAppPath = System.AppDomain.CurrentDomain.BaseDirectory;
        private static int maxSize = (int)(maxSizeM * 1024 * 1024);
        private static FileSystemWatcher watcher = new FileSystemWatcher();
        static void Main(string[] args)
        {

            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.Deleted += new FileSystemEventHandler(OnDeleted);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);

            watcher.Path = rootPath;   //设置监控的文件目录
            watcher.IncludeSubdirectories = true;   //设置监控目录下的所有子目录
            watcher.Filter = "*.*";   //设置监控文件的类型
            watcher.NotifyFilter = NotifyFilters.LastWrite;//NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size;   //设置文件的文件名、目录名及文件的大小改动会触发Changed事件
            watcher.EnableRaisingEvents = true;  //启动监控

            Console.WriteLine("文件监控启动...");
            Console.Read();
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("OnCreated");
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (System.IO.Directory.Exists(e.FullPath))
            {
                //文件夹
                return;
            }

            FileInfo f = new FileInfo(e.FullPath);
            if (f.Extension.ToString() != ".jpg" &&
                f.Extension.ToString() != ".png" &&
                f.Extension.ToString() != ".mp4")
            {
                return;
            }

            Thread.Sleep(100);
            string ossPath = e.Name.Replace("\\", "/");
            YFLog.logInfo("OnChanged{0}", e.Name);

            /////文件压缩
            if (f.Extension.ToString() == ".jpg" && f.Length > maxSize)
            {
                string tempFilePath1 = string.Format("{2}\\temp\\{0}{1}", Guid.NewGuid().ToString("N"), f.Extension.ToString(), baseAppPath);
                f.CopyTo(tempFilePath1);
                string tempFilePath2 = string.Format("{0}.tmp", e.FullPath);

                System.Drawing.Image iSource = System.Drawing.Image.FromFile(tempFilePath1);
                OrientationImage(iSource);
                compressImage(iSource, tempFilePath2, 100);

                File.Delete(e.FullPath);
                File.Move(tempFilePath2, e.FullPath);
                File.Delete(tempFilePath1);

                YFLog.logInfo("compressImage success {0}", e.Name);
            }

            //文件上传
            AliPutObject.AsyncPutObject(ossPath, e.FullPath);
        }
        private static void OnDeleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("OnDeleted");
        }
        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine("OnRenamed");
        }


        private static bool compressImage(Image iSource, string dFile, int flag)
        {

            ImageFormat tFormat = iSource.RawFormat;
            int dWidth = 2000;//iSource.Width / 2;
            int dHeight = (dWidth * iSource.Height) / iSource.Width;//iSource.Height / 2;            
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > maxSize)
                    {
                        flag = flag - 10;
                        compressImage(iSource, dFile, flag);
                    }
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }


        public static void OrientationImage(Image image)
        {
            if (Array.IndexOf(image.PropertyIdList, 274) > -1)
            {
                var orientation = (int)image.GetPropertyItem(274).Value[0];
                switch (orientation)
                {
                    case 1:
                        // No rotation required.
                        break;
                    case 2:
                        image.RotateFlip(RotateFlipType.RotateNoneFlipX);
                        break;
                    case 3:
                        image.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        break;
                    case 4:
                        image.RotateFlip(RotateFlipType.Rotate180FlipX);
                        break;
                    case 5:
                        image.RotateFlip(RotateFlipType.Rotate90FlipX);
                        break;
                    case 6:
                        image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        break;
                    case 7:
                        image.RotateFlip(RotateFlipType.Rotate270FlipX);
                        break;
                    case 8:
                        image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        break;
                }
                image.RemovePropertyItem(274);
            }
        }
    }
}
